package com.mystudy.concurrent.designModel.observerModel.thread;

import java.util.List;

/**
 * TODO:
 *
 * @author acy
 * @since 2019/05/27 21:08
 */
public class ThreadLifeCycleObserver implements LifeCycleListener {
	private final Object LOCK = new Object();

	public void concurrentQuery(List<String> ids) {
		if (ids == null || ids.isEmpty()) {
			return;
		}
		ids.forEach(id -> {
			new Thread(new ObservableRunnable(this) {
				@Override
				public void run() {
					try {
						notifyStateChanged(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
						System.out.println("query for the id" + id);
						Thread.sleep(1000l);
						notifyStateChanged(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));
					} catch (InterruptedException e) {
						notifyStateChanged(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
						e.printStackTrace();
					}
				}
			}, id).start();
		});
	}

	@Override
	public void onStateChangeEvent(ObservableRunnable.RunnableEvent runnableEvent) {
		synchronized (LOCK) {
			System.out.println("the runnable [" + runnableEvent.getThread().getState() + "] date changed and state is [" + runnableEvent.getState() + "]");
			if (runnableEvent.getState() == null) {
				System.out.println("thred cause by +[" + runnableEvent.getThrowable() + "]");
				runnableEvent.getThrowable().printStackTrace();
			}
		}
	}
}
